<template>
  <Tabs v-model="currentPane">
    <TabPane label="数据" name="datas" icon="md-apps" :style="{ maxHeight: paneHeight + 'px' }">
      <Table border stripe :highlight-row="true" :height="tableHeight" :columns="columnNames" :data="rows">
        <template slot-scope="{ row, index }" slot="index">{{ offsets + index + 1 }}</template>
      </Table>
      <Page ref="pager" :total="total" :page-size="20" show-total show-elevator @on-change="OnPaged" style="margin-top:5px;" />
    </TabPane>
    <TabPane label="数据过滤" name="filter" icon="md-search" style="padding: 0 10px;">
      <Form :label-width="1">
        <Row v-for="(item, index) in conditions" :key="'condition:' + index">
          <template v-if="index > 0">
            <form-field
              label=""
              :label-width="1"
              :span="2"
              type="select"
              v-model="item.join"
              :datas="[
                { text: '并且', value: 'and' },
                { text: '或者', value: 'or' }
              ]"
            />
          </template>
          <template v-else>
            <Col :span="1">&nbsp;</Col>
          </template>
          <Col :span="6"><form-field label="" :label-width="1" type="select" v-model="item.field" :datas="fields"/></Col>
          <Col :span="3"><form-field label="" :label-width="1" type="select" v-model="item.op" :datas="operations"/></Col>
          <Col :span="11"><form-field label="" :label-width="1" type="input" v-model="item.value"/></Col>
          <Col :span="3">
            <form-field :label-width="1" type="input" style="text-align:left;">
              <ButtonGroup shape="circle">
                <Button icon="md-add-circle" type="primary" @click="OnAddCondition(index)"></Button>
                <Button icon="md-remove" type="error" @click="OnRemoveCondition(index)"></Button>
              </ButtonGroup>
            </form-field>
          </Col>
        </Row>
        <Row>
          <Col :span="16">&nbsp;</Col>
          <Col :span="8" style="text-align:right;">
            <ButtonGroup shape="circle">
              <Button icon="ios-search" type="primary" @click="OnSearchData()">搜索</Button>
              <Button icon="ios-trash" type="danger" @click="ClearConditions">清除查询</Button>
              <Button icon="ios-arrow-back" type="default" @click="currentPane = 'datas'">返回</Button>
            </ButtonGroup>
          </Col>
        </Row>
      </Form>
    </TabPane>
  </Tabs>
</template>

<script>
export default {
  data() {
    return {
      total: 0,
      offsets: 0,
      columns: [],
      rows: [],
      showSearch: false,
      fields: [],
      currentPane: 'datas',
      formData: {},
      operations: [
        {
          text: '等于',
          value: '='
        },
        {
          text: '大于',
          value: '>'
        },
        {
          text: '大于等于',
          value: '>='
        },
        {
          text: '小于',
          value: '<'
        },
        {
          text: '小于等于',
          value: '<='
        },
        {
          text: '包含',
          value: 'LIKE'
        }
      ],
      conditions: [
        {
          op: '='
        }
      ]
    };
  },
  computed: {
    paneHeight() {
      return this.$store.state.area.tableDetail.height - 65;
    },
    tableHeight() {
      return this.$store.state.area.tableDetail.height - 105;
    },
    columnNames() {
      if (this.columns && this.columns.length > 0) {
        this.fields.length = 0;

        var columnNames = this.columns.map(item => {
          let rtitle = item.title.replace(/（/g, '(').replace(/）/g, ')');
          let title = rtitle.indexOf('(') != -1 ? rtitle.substring(0, rtitle.indexOf('(')) : rtitle;

          title = title.replace('/：/ig', ':');
          title = title.indexOf(':') != -1 ? title.substring(0, title.indexOf(':')) : title;

          let fieldWidth = (item.length || 20) * 15;
          let titleWidth = title.length * 35;

          let width = fieldWidth < 100 ? 100 : fieldWidth < titleWidth ? titleWidth : fieldWidth;

          this.fields.push({
            text: title,
            value: item.field
          });

          return {
            key: item.field,
            title: title,
            width: width > 300 ? 300 : width,
            ellipsis: true,
            tooltip: true,
            resizable: true,
            renderHeader: (h, data) => {
              return h(
                'Tooltip',
                {
                  props: {
                    transfer: true,
                    placement: 'top-start',
                    content: data.column.title
                  }
                },
                [h('span', data.column.title)]
              );
            }
          };
        });

        // 添加序号
        columnNames.unshift({
          key: 'index',
          title: '序号',
          width: 90,
          align: 'center',
          slot: 'index'
        });

        return columnNames;
      } else {
        return [];
      }
    }
  },
  watch: {
    $route: function(to) {
      this.$nextTick(() => {
        this.ClearConditions();
        this.$refs.pager.currentPage = 1;

        this.OnPaged();
      });
    }
  },
  methods: {
    OnPaged(index = 1) {
      let dbIndex = this.$route.params.dbIndex;
      let schema = this.$route.params.schema;
      let tableName = this.$route.params.tableName;
      let pageSize = this.$refs.pager.currentPageSize;

      if (dbIndex && schema && tableName) {
        this.offsets = pageSize * (index - 1);

        let url = `/api/${this.$route.query.dbtype}/${dbIndex}/${schema}/${tableName}/datas`;
        let so = { pageIndex: index, pageSize: pageSize, filters: this.conditions };

        this.$http.post(url, so).then(res => {
          this.total = res.total;
          this.columns = res.columns;
          this.rows = res.datas;
        });
      }
    },
    OnAddCondition(index) {
      this.conditions.splice(index + 1, 0, {
        op: '=',
        join: 'and'
      });
    },
    OnRemoveCondition(index) {
      if (this.conditions.length == 1) {
        this.$Message.warning('必须保留一个查询条件！');

        return;
      }

      this.conditions.splice(index, 1);
    },
    OnSearchData() {
      this.OnPaged();
      this.currentPane = 'datas';
    },
    ClearConditions() {
      this.conditions.length = 0;
      this.conditions.push({
        op: '='
      });
    }
  },
  mounted() {
    this.OnPaged();
  }
};
</script>
<style lang="less" scoped>
.ivu-form-item {
  margin-bottom: 10px;
}

th .ivu-table-cell {
  white-space: nowrap;
  word-break: keep-all;
}
</style>
